package com.pickup.kafka.consumer;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.pickup.pojo.Users;
import com.pickup.resp.JSONResult;
import com.pickup.service.LogService;
import com.pickup.utils.JsonUtils;
import com.pickup.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

// 消息消费者
@Component
@Slf4j
public class KafkaConsumer {


    @Autowired
    private ConsumerFactory<String, String> consumerFactory;

    @Autowired
    private LogService logService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private KafkaListenerEndpointRegistry registry;

    // topicPartitions = {@TopicPartition(topic = "ChatMsg", partitionOffsets = @PartitionOffset(partition = "0", initialOffset = "0")),
    @KafkaListener(id = "log", containerFactory = "containerFactory", topics = {"logMessage"})
    public void LogMessage(ConsumerRecords<String, String> records, Acknowledgment ack) {
        for (ConsumerRecord<?, ?> record : records) {
            // System.out.println("*: " + record.value() + "  key: " + record.key() + " offset: " + record.offset() + " partition: " + record.partition());
            logService.saveLog((String) record.value());
            ack.acknowledge();
        }
    }

    @KafkaListener(id = "sms", containerFactory = "containerFactory", topics = {"smsMessage"})
    public void SmsMessage(ConsumerRecords<String, String> records, Acknowledgment ack) throws ClientException {
        for (ConsumerRecord<?, ?> record : records) {

            Users user = JsonUtils.jsonToPojo((String) record.value(), Users.class);
            // 把数据保存在Redis中， 并发一分钟短信给用户
            String smsCode = RandomStringUtils.randomNumeric(6);
            SendSmsResponse sendSmsResponse = smsUtils.sendSms(user.getCellphone(), smsCode);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                redisTemplate.opsForValue().set("pickup-" + user.getCellphone(), smsCode, 1, TimeUnit.SECONDS);
                ack.acknowledge();
            }
        }
    }
}
